import React, { useState } from "react";
import { Page, useNavigate } from "zmp-ui";
import { useI18n } from "../i18n";
import Navbar from "../components/navbar";
import { validateScanCode } from "../api/endpoints";
import { scanQRCode } from "zmp-sdk";

const ScanPage: React.FunctionComponent = () => {
  const { t } = useI18n();
  const navigate = useNavigate();
  const [isScanning, setIsScanning] = useState(false);
  const [isValidating, setIsValidating] = useState(false);
  const [validationError, setValidationError] = useState<string>("");
  const [manualInputValue, setManualInputValue] = useState("");

  const handleScan = async () => {
    try {
      setIsScanning(true);
      setValidationError("");
      
      // 使用 ZMP SDK 的扫码功能
      const result = await scanQRCode();
      console.log('扫码结果:', result);
      
      if (result && result.content) {
        // 从扫码结果中提取设备ID
        const deviceId = extractDeviceId(result.content);
        if (deviceId) {
          // 直接跳转到结果页面，传递设备ID，替换当前页面
          navigate('/scan-result', { state: { scanResult: deviceId }, replace: true });
        } else {
          setValidationError('这不是正确的柜机二维码!');
        }
      }
    } catch (error) {
      console.error('扫码失败:', error);
      setValidationError('扫码失败，请重试');
    } finally {
      setIsScanning(false);
    }
  };

  // 处理SN码并跳转
  const handleSNCode = (snCode: string) => {
    try {
      setIsValidating(true);
      setValidationError("");
      
      if (!snCode.trim()) {
        setValidationError('请输入机柜SN码!');
        return;
      }
      
      console.log('处理SN码:', snCode);
      
      // 直接跳转到结果页面，传递SN码，替换当前页面
      navigate('/scan-result', { state: { scanResult: snCode.trim() }, replace: true });
    } catch (error) {
      console.error('处理SN码失败:', error);
      setValidationError('处理失败，请重试');
    } finally {
      setIsValidating(false);
    }
  };

  // 从扫码结果中提取设备ID
  const extractDeviceId = (result: string): string | null => {
    try {
      const url = new URL(result);
      console.log('url:', url);
      const deviceId = url.searchParams.get('id') || url.searchParams.get('deviceId');
      return deviceId;
    } catch {
      // 如果不是URL格式，尝试其他解析方式
      const match = result.match(/(?:id|deviceId)[=:]([A-Za-z0-9]+)/);
      return match ? match[1] : null;
    }
  };


  const handleConfirmManualInput = () => {
    if (manualInputValue.trim()) {
      console.log('手动输入:', manualInputValue);
      // 直接处理SN码并跳转
      handleSNCode(manualInputValue.trim());
      setManualInputValue("");
    }
  };


  return (
    <Page className="page" style={{ padding: 0, background: '#F5F5F7' }}>
      {/* 顶部导航栏 */}
      <Navbar title={t("scan.title")} />

      {/* 内容区域 */}
      <div style={{
        padding: '20px',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        minHeight: 'calc(100vh - 60px)',
        background: 'linear-gradient(180deg, #E8F5E8 0%, #2D5A2D 100%)',
        position: 'relative'
      }}>
        {/* 装饰性圆形元素 */}
        <div style={{
          position: 'absolute',
          top: '20px',
          left: '20px',
          width: '60px',
          height: '60px',
          borderRadius: '50%',
          background: 'rgba(255, 255, 255, 0.2)',
          border: '2px solid rgba(255, 255, 255, 0.3)'
        }} />
        
        {/* 装饰性线条 */}
        <div style={{
          position: 'absolute',
          top: '50px',
          left: '80px',
          width: '2px',
          height: '100px',
          background: 'linear-gradient(180deg, rgba(255, 255, 255, 0.4) 0%, rgba(255, 255, 255, 0.1) 100%)',
          transform: 'rotate(15deg)'
        }} />

        {/* 机柜SN输入区域 */}
        <div style={{
          width: '100%',
          maxWidth: 300,
          display: 'flex',
          alignItems: 'center',
          marginBottom: '30px',
          gap: '10px'
        }}>
          <input
            type="text"
            placeholder={t("scan.cabinetSN")}
            value={manualInputValue}
            onChange={(e) => setManualInputValue(e.target.value)}
            onKeyPress={(e) => {
              if (e.key === 'Enter') {
                handleConfirmManualInput();
              }
            }}
            style={{
              flex: 1,
              height: '50px',
              padding: '0 15px',
              backgroundColor: 'rgba(255, 255, 255, 0.9)',
              border: '1px solid rgba(255, 255, 255, 0.3)',
              borderRadius: '25px',
              fontSize: '16px',
              color: '#333',
              backdropFilter: 'blur(10px)',
              outline: 'none'
            }}
            onFocus={(e) => {
              e.target.style.borderColor = 'rgba(255, 255, 255, 0.6)';
            }}
            onBlur={(e) => {
              e.target.style.borderColor = 'rgba(255, 255, 255, 0.3)';
            }}
          />
          <button
            onClick={handleConfirmManualInput}
            style={{
              width: '50px',
              height: '50px',
              backgroundColor: '#000',
              color: '#fff',
              border: 'none',
              borderRadius: '8px',
              fontSize: '20px',
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              transition: 'all 0.2s'
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.backgroundColor = '#333';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.backgroundColor = '#000';
            }}
          >
            ›
          </button>
        </div>

        {/* 扫码区域 */}
        <div style={{
          width: '100%',
          maxWidth: 300,
          height: 300,
          border: '2px solid rgba(255, 255, 255, 0.3)',
          borderRadius: '12px',
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          backgroundColor: 'rgba(255, 255, 255, 0.1)',
          backdropFilter: 'blur(10px)',
          marginBottom: '30px',
          position: 'relative',
          overflow: 'hidden',
          boxShadow: '0 8px 32px rgba(0, 0, 0, 0.1)'
        }}>
          {/* 扫码框角标 */}
          <div style={{
            position: 'absolute',
            top: 20,
            left: 20,
            width: 30,
            height: 30,
            borderTop: '3px solid #fff',
            borderLeft: '3px solid #fff'
          }} />
          <div style={{
            position: 'absolute',
            top: 20,
            right: 20,
            width: 30,
            height: 30,
            borderTop: '3px solid #fff',
            borderRight: '3px solid #fff'
          }} />
          <div style={{
            position: 'absolute',
            bottom: 20,
            left: 20,
            width: 30,
            height: 30,
            borderBottom: '3px solid #fff',
            borderLeft: '3px solid #fff'
          }} />
          <div style={{
            position: 'absolute',
            bottom: 20,
            right: 20,
            width: 30,
            height: 30,
            borderBottom: '3px solid #fff',
            borderRight: '3px solid #fff'
          }} />

          {/* 扫码提示 */}
          <div style={{
            textAlign: 'center',
            color: 'rgba(255, 255, 255, 0.9)',
            fontSize: 14,
            fontWeight: '500'
          }}>
            {isScanning ? t("scan.scanning") : t("scan.placeQRCode")}
          </div>

          {/* 扫描线动画 */}
          {isScanning && (
            <div style={{
              position: 'absolute',
              top: '50%',
              left: 0,
              right: 0,
              height: '2px',
              backgroundColor: '#fff',
              boxShadow: '0 0 10px rgba(255, 255, 255, 0.8)',
              animation: 'scanLine 2s linear infinite'
            }} />
          )}
        </div>

        {/* 扫码按钮 */}
        <button
          onClick={handleScan}
          disabled={isScanning}
          style={{
            width: '100%',
            maxWidth: 300,
            height: 50,
            backgroundColor: isScanning ? 'rgba(255, 255, 255, 0.3)' : 'rgba(255, 255, 255, 0.9)',
            color: isScanning ? 'rgba(255, 255, 255, 0.6)' : '#2D5A2D',
            border: 'none',
            borderRadius: '25px',
            fontSize: 16,
            fontWeight: 'bold',
            cursor: isScanning ? 'not-allowed' : 'pointer',
            marginBottom: '15px',
            transition: 'all 0.2s',
            backdropFilter: 'blur(10px)',
            boxShadow: '0 4px 16px rgba(0, 0, 0, 0.1)'
          }}
        >
          {isScanning ? t("scan.scanning") : t("scan.startScan")}
        </button>

      </div>

      {/* 扫描线动画样式 */}
      <style>
        {`
          @keyframes scanLine {
            0% { transform: translateY(-150px); }
            100% { transform: translateY(150px); }
          }
        `}
      </style>
    </Page>
  );
};

export default ScanPage;
